﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.IO;
using MalkiSumWeb.Models;
using MalikSumLib.Utilities;
using Telerik.Web.Mvc;

namespace MalkiSumWeb.Controllers
{
    public class FilesController : Controller
    {
        //
        // GET: /Files/

        public ActionResult Index()
        {
            return View();
        }


        public ActionResult AddFile()
        {
            ViewData["error"] = "";
            ViewData["errorDetails"] = "";
            return View();
        }

        /*
                    string ext1 = System.IO.Path.ChangeExtension(FilePath,"pdf");
                    string ext2 = System.IO.Path.GetDirectoryName(FilePath);
                    string ext3 = System.IO.Path.GetExtension(FilePath);
                    string ext4 = System.IO.Path.GetFileName(FilePath);
                    string ext5 = System.IO.Path.GetFileNameWithoutExtension(FilePath);
                    string ext6 = System.IO.Path.GetFullPath(FilePath);
                    string ext7 = System.IO.Path.GetPathRoot(FilePath);
                    string ext8 = System.IO.Path.GetTempFileName();
                    string ext9 = System.IO.Path.GetTempPath();
        FilePath = "D:\\MyProjects\\Sumarize\\MalkiSum\\Web\\MalkiSumWeb\\Content\\Users\\1000\\Files\\testFileName.doc"
        System.IO.Path.ChangeExtension(FilePath,"pdf")= "D:\MyProjects\Sumarize\MalkiSum\Web\MalkiSumWeb\Content\Users\1000\Files\testFileName.pdf"
        System.IO.Path.GetDirectoryName(FilePath) ="D:\\MyProjects\\Sumarize\\MalkiSum\\Web\\MalkiSumWeb\\Content\\Users\\1000\\Files"
        System.IO.Path.GetExtension(FilePath) = ".doc"
        System.IO.Path.GetFileName(FilePath) = "testFileName.doc"
        System.IO.Path.GetFileNameWithoutExtension(FilePath)="testFileName"
        System.IO.Path.GetFullPath(FilePath) = "D:\\MyProjects\\Sumarize\\MalkiSum\\Web\\MalkiSumWeb\\Content\\Users\\1000\\Files\\testFileName.doc"
        System.IO.Path.GetPathRoot(FilePath) = "D:\\"
        System.IO.Path.GetTempFileName() = "C:\\Users\\Mohamed\\AppData\\Local\\Temp\\tmp2087.tmp"
        System.IO.Path.GetTempPath() = "C:\\Users\\Mohamed\\AppData\\Local\\Temp\\"
         */
        [HttpPost]
        [ValidateInput(false)]
        public ActionResult ProcessSubmit(IEnumerable<HttpPostedFileBase> attachments,
            int? ddlFields, string keyWords, string editorAddText, string txtType, string txtFileName)
        {
            try
            {
                if (attachments != null && ddlFields != null && txtType == "0")
                {
                    //TempData["UploadedAttachments"] = GetFileInfo(attachments);
                    IEnumerable<string> FileInfo = GetFileInfo(attachments);
                    foreach (var file in attachments)
                    {
                        if (!Directory.Exists(Server.MapPath("~/Content/Users/" + MainController.myUserID + "/Files/")))
                        {
                            Directory.CreateDirectory(Server.MapPath("~/Content/Users/" + MainController.myUserID + "/Files/"));

                            if (!Directory.Exists(Server.MapPath("~/Content/Users/" + MainController.myUserID + "/PDFs/")))
                            {
                                Directory.CreateDirectory(Server.MapPath("~/Content/Users/" + MainController.myUserID + "/PDFs/"));
                            }
                        }

                        string FilePath = Server.MapPath("~/Content/Users/" + MainController.myUserID + "/Files/" + Path.GetFileName(file.FileName));
                        file.SaveAs(FilePath);

                        string PDFPath = Server.MapPath("~/Content/Users/" + MainController.myUserID + "/PDFs/"
                                                            + System.IO.Path.GetFileNameWithoutExtension(FilePath) + ".pdf");

                        PDFManager pdfManager = new PDFManager();
                        pdfManager.ConvertFile(FilePath, PDFPath, Server.MapPath("~/Content/fonts/times.ttf"));



                        Models.File uploadedFile = new Models.File();
                        uploadedFile.Name = Path.GetFileName(file.FileName);
                        uploadedFile.MemberID = MainController.myUserID;
                        uploadedFile.FieldID = ddlFields;
                        uploadedFile.PostDate = DateTime.Now;
                        uploadedFile.KeyWords = keyWords;
                        // لفصل الكلمات عربى وانجليزى
                        // keyWords.Split(',', '،');
                        uploadedFile.FileContent = "";
                        uploadedFile.OriginalUrl = "~/Content/Users/" + MainController.myUserID + "/Files/" + Path.GetFileName(file.FileName);
                        uploadedFile.DownloadUrl = "~/Content/Users/" + MainController.myUserID + "/PDFs/"
                                                        + System.IO.Path.GetFileNameWithoutExtension(FilePath) + ".pdf";
                        uploadedFile.PartNo = 1;
                        uploadedFile.CreatedBy = MainController.myUserID;

                        SumrizDBEntities db = new SumrizDBEntities();
                        db.AddToFiles(uploadedFile);
                        db.SaveChanges();
                    }
                }
                else if (txtType == "1")
                {
                    if (editorAddText != "" && txtFileName != "")
                    {
                        if (!Directory.Exists(Server.MapPath("~/Content/Users/" + MainController.myUserID + "/Files/")))
                        {
                            Directory.CreateDirectory(Server.MapPath("~/Content/Users/" + MainController.myUserID + "/Files/"));

                            if (!Directory.Exists(Server.MapPath("~/Content/Users/" + MainController.myUserID + "/PDFs/")))
                            {
                                Directory.CreateDirectory(Server.MapPath("~/Content/Users/" + MainController.myUserID + "/PDFs/"));
                            }
                        }

                        string PDFPath = Server.MapPath("~/Content/Users/" + MainController.myUserID + "/PDFs/" + txtFileName + ".pdf");

                        PDFManager pdfManager = new PDFManager();
                        //pdfManager.ConvertText(editorAddText, PDFPath); // For basic text
                        pdfManager.ConvertHTMLText(editorAddText, PDFPath, Server.MapPath("~/Content/fonts/times.ttf")); // For HTML text



                        Models.File uploadedFile = new Models.File();
                        uploadedFile.Name = txtFileName;
                        uploadedFile.MemberID = MainController.myUserID;
                        uploadedFile.FieldID = ddlFields;
                        uploadedFile.PostDate = DateTime.Now;
                        uploadedFile.KeyWords = keyWords;
                        // لفصل الكلمات عربى وانجليزى
                        // keyWords.Split(',', '،');
                        uploadedFile.FileContent = "";
                        uploadedFile.OriginalUrl = "";
                        uploadedFile.DownloadUrl = "~/Content/Users/" + MainController.myUserID + "/PDFs/"
                                                        + System.IO.Path.GetFileNameWithoutExtension(txtFileName) + ".pdf";
                        uploadedFile.PartNo = 1;
                        uploadedFile.CreatedBy = MainController.myUserID;

                        SumrizDBEntities db = new SumrizDBEntities();
                        db.AddToFiles(uploadedFile);
                        db.SaveChanges();
                    }
                }
                return View("AddFile");
            }
            catch (Exception ex)
            {
                ViewData["error"] = ex.Message;
                ViewData["errorDetails"] = ex.InnerException.Message;
                return View("AddFile");
            }

        }
        private IEnumerable<string> GetFileInfo(IEnumerable<HttpPostedFileBase> attachments)
        {
            return
                from a in attachments
                where a != null
                select string.Format("{0} ({1} bytes)", Path.GetFileName(a.FileName), a.ContentLength);
        }

        [HttpPost]
        public ActionResult _SelectFields(string text)
        {
            SumrizDBEntities db = new SumrizDBEntities();
            var fields = db.Fields;
            return new JsonResult { Data = new SelectList(fields.ToList(), "ID", "NameEn") };
        }


        [GridAction]
        public ActionResult _MyFavourites()
        {
            SumrizDBEntities db = new SumrizDBEntities();
            var myFavourites = db.Files.Where(f => f.IsDeleted != true //&& f.MemberID == MainController.myUserID 
                    && db.MemberActivities.Where(m => m.FileID == f.ID)
                    .OrderByDescending(x => x.ID).FirstOrDefault().ActionTypeID == 15)
                    .Select(n => new
                    {
                        n.ID,
                        n.Name,
                        n.LikeCount,
                        n.ShareCount,
                        n.ReportCount
                    }).ToList();

            return View(new GridModel(myFavourites));
            //return View(new GridModel<MalkiSumWeb.Models.File>
            //{
            //    Data = myFavourites

            //});
        }
        [AcceptVerbs(HttpVerbs.Post)]
        [GridAction]
        public ActionResult _RemoveFavourites(int ID)
        {
            SumrizDBEntities db = new SumrizDBEntities();

            if (MainController.myUserID > 0)
            {
                    var file = db.Files.Where(F => F.ID == ID).FirstOrDefault();
                    if (file != null)
                    {
                        
                        MemberActivity m = new MemberActivity();
                        m.MemberID = MainController.myUserID;
                        m.FileID = ID;
                        m.ActionTypeID = 16;
                        m.Description = MainController.myFirstName + " " + MainController.myLastName + " removed a file from favourites.";

                        db.MemberActivities.AddObject(m);
                        db.SaveChanges();

                    }
                
            }
            var myFavourites = db.Files.Where(f => f.IsDeleted != true //&& f.MemberID == MainController.myUserID 
                    && db.MemberActivities.Where(m => m.FileID == f.ID)
                    .OrderByDescending(x => x.ID).FirstOrDefault().ActionTypeID == 15)
                    .Select(n => new
                    {
                        n.ID,
                        n.Name,
                        n.LikeCount,
                        n.ShareCount,
                        n.ReportCount
                    }).ToList();

            return View(new GridModel(myFavourites));
            //return View(new GridModel<MalkiSumWeb.Models.File>
            //{
            //    Data = myFavourites

            //});
        }
        public ActionResult FieldView(int cat, string q, int? count, int? UserID, bool? Favourites)
        {
            ViewData["count"] = count;
            SumrizDBEntities db = new SumrizDBEntities();

            var files = db.Files.Where(F => F.IsDeleted == false);

            if (cat > 0)
            {
                files = files.Where(F => F.FieldID == cat);
            }

            if (q != null && q != "")
            {
                files = files.Where(F => F.Name.Contains(q) || F.KeyWords.Contains(q));
            }

            if (UserID.HasValue)
            {
                files = files.Where(f => f.MemberID == UserID);
            }

            if (Favourites.HasValue)
            {
                files = files.Where(f => db.MemberActivities.Where(m => m.FileID == f.ID).OrderByDescending(x => x.ID).FirstOrDefault().ActionTypeID == 15);
            }


            if (files.Count() > 0)
            {
                // order by most views , most download  , posted date 
                if (count.HasValue)
                {
                    return View(files.Take(count.Value).OrderByDescending(f => f.ViewCount).OrderByDescending(f => f.DownloadCount).OrderByDescending(f => f.PostDate.Value));
                }
                else
                {
                    return View(files.OrderByDescending(f => f.ViewCount).OrderByDescending(f => f.DownloadCount).OrderByDescending(f => f.PostDate.Value));
                }
            }
            else
            {
                return View();
            }

        }
        public JsonResult deleteFile(string id)
        {
            bool success = false;
            string msg = "";
            if (MainController.myUserID > 0)
            {
                SumrizDBEntities db = new SumrizDBEntities();
                int ID = 0;
                bool converted = int.TryParse(id, out ID);
                if (converted)
                {
                    var file = db.Files.Where(F => F.ID == ID).FirstOrDefault();
                    if (file != null)
                    {
                        file.IsDeleted = true;

                        MemberActivity m = new MemberActivity();
                        m.MemberID = MainController.myUserID;
                        m.FileID = ID;
                        m.ActionTypeID = 10;
                        m.Description = MainController.myFirstName + " " + MainController.myLastName + " has deleted a file with ID = " + ID;

                        db.MemberActivities.AddObject(m);
                        db.SaveChanges();
                        success = true;

                    }
                    else
                    {
                        msg = "File not found.";
                        success = false;
                    }
                }
                else
                {
                    msg = "Invalid file id.";
                    success = false;
                }
            }
            else
            {
                msg = "Please login first.";
                success = false;
            }
            return Json(new
            {
                msg = msg,
                success = success
            });
        }
        public JsonResult like(string id)
        {
            bool success = false;
            string msg = "";
            if (MainController.myUserID > 0)
            {
                SumrizDBEntities db = new SumrizDBEntities();
                int ID = 0;
                bool converted = int.TryParse(id, out ID);
                if (converted)
                {
                    var file = db.Files.Where(F => F.ID == ID).FirstOrDefault();
                    if (file != null)
                    {
                        if (file.LikeCount.HasValue)
                        {
                            file.LikeCount = file.LikeCount + 1;
                        }
                        else
                        {
                            file.LikeCount = 1;
                        }
                        MemberActivity m = new MemberActivity();
                        m.MemberID = MainController.myUserID;
                        m.FileID = ID;
                        m.ActionTypeID = 11;
                        m.Description = MainController.myFirstName + " " + MainController.myLastName + " has liked a file";

                        db.MemberActivities.AddObject(m);
                        db.SaveChanges();
                        success = true;

                    }
                    else
                    {
                        msg = "File not found.";
                        success = false;
                    }
                }
                else
                {
                    msg = "Invalid file id.";
                    success = false;
                }
            }
            else
            {
                msg = "Please login first.";
                success = false;
            }
            return Json(new
            {
                msg = msg,
                success = success
            });
        }

        public JsonResult unlike(string id)
        {
            bool success = false;
            string msg = "";
            if (MainController.myUserID > 0)
            {
                SumrizDBEntities db = new SumrizDBEntities();
                int ID = 0;
                bool converted = int.TryParse(id, out ID);
                if (converted)
                {
                    var file = db.Files.Where(F => F.ID == ID).FirstOrDefault();
                    if (file != null)
                    {
                        if (file.LikeCount.HasValue)
                        {
                            file.LikeCount = file.LikeCount - 1;
                        }
                        else
                        {
                            file.LikeCount = 0;
                        }
                        MemberActivity m = new MemberActivity();
                        m.MemberID = MainController.myUserID;
                        m.FileID = ID;
                        m.ActionTypeID = 12;
                        m.Description = MainController.myFirstName + " " + MainController.myLastName + " has unliked a file";

                        db.MemberActivities.AddObject(m);
                        db.SaveChanges();

                        success = true;

                    }
                    else
                    {
                        msg = "File not found.";
                        success = false;
                    }
                }
                else
                {
                    msg = "Invalid file id.";
                    success = false;
                }
            }
            else
            {
                msg = "Please login first.";
                success = false;
            }
            return Json(new
            {
                msg = msg,
                success = success
            });
        }

        public JsonResult AddToFavourites(string id)
        {
            bool success = false;
            string msg = "";
            if (MainController.myUserID > 0)
            {
                SumrizDBEntities db = new SumrizDBEntities();
                int ID = 0;
                bool converted = int.TryParse(id, out ID);
                if (converted)
                {
                    var file = db.Files.Where(F => F.ID == ID).FirstOrDefault();
                    if (file != null)
                    {
                        if (file.FavoriteCount.HasValue)
                        {
                            file.FavoriteCount = file.FavoriteCount + 1;
                        }
                        else
                        {
                            file.FavoriteCount = 1;
                        }
                        MemberActivity m = new MemberActivity();
                        m.MemberID = MainController.myUserID;
                        m.FileID = ID;
                        m.ActionTypeID = 15;
                        m.Description = MainController.myFirstName + " " + MainController.myLastName + " added a file to favourites.";

                        db.MemberActivities.AddObject(m);
                        db.SaveChanges();
                        success = true;

                    }
                    else
                    {
                        msg = "File not found.";
                        success = false;
                    }
                }
                else
                {
                    msg = "Invalid file id.";
                    success = false;
                }
            }
            else
            {
                msg = "Please login first.";
                success = false;
            }
            return Json(new
            {
                msg = msg,
                success = success
            });
        }

        public JsonResult RemoveFromFavourites(string id)
        {
            bool success = false;
            string msg = "";
            if (MainController.myUserID > 0)
            {
                SumrizDBEntities db = new SumrizDBEntities();
                int ID = 0;
                bool converted = int.TryParse(id, out ID);
                if (converted)
                {
                    var file = db.Files.Where(F => F.ID == ID).FirstOrDefault();
                    if (file != null)
                    {                       
                        MemberActivity m = new MemberActivity();
                        m.MemberID = MainController.myUserID;
                        m.FileID = ID;
                        m.ActionTypeID = 16;
                        m.Description = MainController.myFirstName + " " + MainController.myLastName + " removed a file from favourites.";

                        db.MemberActivities.AddObject(m);
                        db.SaveChanges();

                        success = true;

                    }
                    else
                    {
                        msg = "File not found.";
                        success = false;
                    }
                }
                else
                {
                    msg = "Invalid file id.";
                    success = false;
                }
            }
            else
            {
                msg = "Please login first.";
                success = false;
            }
            return Json(new
            {
                msg = msg,
                success = success
            });
        }

        public ActionResult share(string id)
        {
            if (MainController.myUserID > 0)
            {
                SumrizDBEntities db = new SumrizDBEntities();
                int ID = 0;
                bool converted = int.TryParse(id, out ID);
                if (converted)
                {
                    var file = db.Files.Where(F => F.ID == ID).FirstOrDefault();
                    if (file != null)
                    {
                        if (file.ShareCount.HasValue)
                        {
                            file.ShareCount = file.ShareCount + 1;
                        }
                        else
                        {
                            file.ShareCount = 1;
                        }
                        MemberActivity m = new MemberActivity();
                        m.MemberID = MainController.myUserID;
                        m.FileID = ID;
                        m.ActionTypeID = 17;
                        m.Description = MainController.myFirstName + " " + MainController.myLastName + " has shared a file";

                        db.SaveChanges();
                    }
                }
            }
            return null;
        }

        public ActionResult download(string id)
        {
            SumrizDBEntities db = new SumrizDBEntities();
            int ID = 0;
            bool converted = int.TryParse(id, out ID);
            if (converted)
            {
                var file = db.Files.Where(F => F.ID == ID).FirstOrDefault();
                if (file != null)
                {
                    if (file.DownloadCount.HasValue)
                    {
                        file.DownloadCount = file.DownloadCount + 1;
                    }
                    else
                    {
                        file.DownloadCount = 1;
                    }
                    db.SaveChanges();
                    return File(file.DownloadUrl, "text/PDF", Path.GetFileNameWithoutExtension(file.Name) + ".pdf");

                }
            }
            return null;
        }



        public ActionResult FileViewer(string id)
        {
            SumrizDBEntities db = new SumrizDBEntities();
            int ID = 0;
            bool converted = int.TryParse(id, out ID);
            if (converted)
            {
                var file = db.Files.Where(F => F.ID == ID).FirstOrDefault();
                if (file != null)
                {
                    if (file.ViewCount.HasValue)
                    {
                        file.ViewCount = file.ViewCount + 1;
                    }
                    else
                    {
                        file.ViewCount = 1;
                    }
                    db.SaveChanges();

                    //FileStream fileStream = new FileStream(Server.MapPath(file.DownloadUrl), FileMode.Open, FileAccess.Read);                   

                    //Response.AddHeader("Content-Disposition", "inline; filename=Authorization.pdf");

                    //return View(fileStream);
                    ViewData["path"] = file.DownloadUrl;
                    return View();


                }
            }
            return null;
        }

        public FileStreamResult GetPDF(string path)
        {
            FileStream fs = new FileStream(Server.MapPath(path), FileMode.Open, FileAccess.Read);
            return File(fs, "application/pdf");
        }
    }
}
